package com.gaogis.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gaogis.platform.Response;
import com.gaogis.platform.domain.Analysis;
import com.gaogis.platform.domain.Analysiss;
import com.gaogis.platform.dto.AnalysisDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

@RestController
public class AnalysisController {


	@Value("${db.dir}")
	private String dbDir;

	private String dbName="db2.json";



	public static String generateId() {
        	return UUID.randomUUID().toString().replace("-","");
    	}
	
	/**
 	 * 添加收藏
 	 */
	@PostMapping(value="/analysis/{uid}/add")
	public Object addAnalysis(@PathVariable("uid") String uid,@Valid @RequestBody AnalysisDto dto){
		Map<String,Analysiss> map = getAnalysiss();
		Analysiss analysiss=null;
		if(map.containsKey(uid)){
			analysiss = map.get(uid);
		}else{
			analysiss = new Analysiss(uid);
			map.put(uid,analysiss);
		}
		Analysis fav=new Analysis(generateId(),dto.date,dto.name,dto.lnglat,dto.zoom,dto.expression);
		fav.pid = getMaxPid(analysiss);
		fav.description=dto.description;
		if(analysiss.analysiss==null){
			analysiss.analysiss=new ArrayList<Analysis>();
		}
		analysiss.analysiss.add(fav);
		List<Analysiss> fs=new ArrayList<Analysiss>();
		for(String key:map.keySet()){
			fs.add(map.get(key));
		}
		saveAnalysiss(fs);
		return Response.success(null);
	}

	private Integer getMaxPid(Analysiss fs){
		int pid=0;
		if(fs.analysiss!=null){
			for(Analysis f:fs.analysiss){
				Integer i=f.pid;
				if(i!=null && i>pid){
					pid=i;
				}
			}
		}
		return pid+1;
	}

	private synchronized boolean saveAnalysiss(List<Analysiss> list){
		String content=JSONObject.toJSONString(list);
		File f=new File(dbDir,dbName);
		try{
			FileWriter writer = new FileWriter(f);
			writer.write(content);
			writer.flush();
			writer.close();
		}catch(IOException ioe){
			ioe.printStackTrace();
			return false;	
		}
		return true;
	}


        private synchronized boolean saveAnalysiss(Map<String,Analysiss> map){
 
		List<Analysiss> fs=new ArrayList<Analysiss>();
                for(String key:map.keySet()){
                        fs.add(map.get(key));
                }
                return saveAnalysiss(fs);
        }

	private synchronized  Map<String,Analysiss> getAnalysiss(){
		File folder=new File(dbDir);
		if(!folder.exists()){
			folder.mkdir();
		}
    	 	File file=new File(dbDir,dbName);
		Map<String,Analysiss> result=new HashMap<String,Analysiss>();
		if(!file.exists()){
			return result;
		}
		try{
			FileReader fileReader = new FileReader(file);
			StringBuilder jsonContent = new StringBuilder();
		        int character;
        	    	while ((character = fileReader.read()) != -1) {
                		jsonContent.append((char) character);
	            	}
		        fileReader.close();	
			JSONArray jsonArray=JSON.parseArray(jsonContent.toString());
			if(jsonArray!=null){
				List<Analysiss> analysiss = JSON.parseArray(jsonArray.toJSONString(),Analysiss.class);
				if(analysiss!=null && analysiss.size()>0){
					for(Analysiss f:analysiss){
						result.put(f.uid,f);
					}
				}
			}else{
				System.out.println("xxx");
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		return result;
		
	}

	/**
	 * 删除收藏
	 */
	@PostMapping(value="/analysis/{uid}/delete/{analysisid}")
	public Object deleteAnalysis(@PathVariable("uid") String uid,@PathVariable("analysisid") String analysisid){
		Map<String,Analysiss> map=getAnalysiss();
		if(!map.containsKey(uid)){
			return Response.fail("不存在");
		}
		Analysiss fs= map.get(uid);
		if(fs.analysiss==null){
			return Response.fail("不存在");
		}
		for(Analysis f:fs.analysiss){
			if(f.id.equals(analysisid)){
				fs.analysiss.remove(f);
				saveAnalysiss(map);
				return Response.success(null);
				
				
			}
		}
		return Response.fail("不存在");
	}

	private Analysis getAnalysis(String uid,String fid,Map<String,Analysiss> fs){
		if(fs!=null)
		{
			if(fs.containsKey(uid)){
				Analysiss fss=fs.get(uid);
				if(fss!=null){
					if(fss.analysiss!=null){
						for(Analysis f:fss.analysiss){
							if(f.id.equals(fid)){
								return f;
							}
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 查询收藏
	 */
	@GetMapping(value="/analysis/list/{uid}")
	public Object listAnalysis( @PathVariable("uid") String uid){
		Map<String,Analysiss> list=getAnalysiss();
		if(list.containsKey(uid)){
			return Response.success(list.get(uid));
		}
		else{
			return Response.success(new Analysiss(uid));
		}
	}

}
